using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public class RegistrationForm : Form
    {
        private Panel headerPanel;
        private Panel leftPanel;
        private Panel rightPanel;
        private Panel bottomPanel;
        
        // 当前用户信息
        private int currentUserId;
        private string currentUserName;
        
        // 左侧患者选择区域
        private Label lblPatientTitle;
        private ComboBox cmbPatients;
        private Button btnRefreshPatients;
        private Label lblPatientInfo;
        
        // 右侧科室和医生选择区域
        private Label lblDepartmentTitle;
        private TreeView tvDepartments;
        private Label lblDoctorTitle;
        private DataGridView dgvDoctors;
        
        // 挂号信息区域
        private Label lblRegistrationInfo;
        private Label lblSelectedPatient;
        private Label lblSelectedDepartment;
        private Label lblSelectedDoctor;
        private Label lblRegistrationFee;
        
        // 按钮区域
        private Button btnRegister;
        private Button btnCancel;
        
        // 数据存储
        private List<PatientInfo> patients = new List<PatientInfo>();
        private List<DepartmentInfo> departments = new List<DepartmentInfo>();
        private List<DoctorInfo> doctors = new List<DoctorInfo>();
        private DepartmentInfo selectedDepartment;
        private DoctorInfo selectedDoctor;

        public RegistrationForm(int userId)
        {
            this.currentUserId = userId;
          
            InitializeComponent();
            SetupEventHandlers();
            LoadInitialData();
        }

        public RegistrationForm(int userId, string userName)
        {
            this.currentUserId = userId;
            this.currentUserName = userName;
            InitializeComponent();
            SetupEventHandlers();
            LoadInitialData();
        }



        private void InitializeComponent()
        {
            // 设置窗体基本属性
            this.Size = new Size(1200, 850);
            this.Text = "病人挂号";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = UIStyleManager.BackgroundColor;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 创建头部面板
            headerPanel = new Panel
            {
                Size = new Size(1200, 80),
                BackColor = UIStyleManager.PrimaryColor,
                Dock = DockStyle.Top
            };

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.User,
                Font = new Font("Segoe UI Emoji", 24),
                ForeColor = Color.White,
                Location = new Point(30, 20),
                AutoSize = true
            };

            Label titleLabel = new Label
            {
                Text = "病人挂号系统",
                Font = UIStyleManager.TitleFont,
                ForeColor = Color.White,
                Location = new Point(80, 25),
                AutoSize = true
            };

            headerPanel.Controls.Add(lblTitleIcon);
            headerPanel.Controls.Add(titleLabel);

            // 创建底部按钮面板
            bottomPanel = new Panel
            {
                Size = new Size(1200, 70),
                BackColor = Color.FromArgb(240, 240, 240),
                Dock = DockStyle.Bottom
            };

            CreateButtons();

            // 创建左侧面板（患者选择）
            leftPanel = new Panel
            {
                Size = new Size(400, 680),
                Location = new Point(20, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
            };

            CreatePatientSelectionArea();

            // 创建右侧面板（科室和医生）
            rightPanel = new Panel
            {
                Size = new Size(750, 680),
                Location = new Point(430, 90),
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle,
                Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
            };

            CreateDepartmentAndDoctorArea();

            // 添加面板到窗体
            this.Controls.Add(headerPanel);
            this.Controls.Add(bottomPanel);
            this.Controls.Add(leftPanel);
            this.Controls.Add(rightPanel);
        }

        private void CreatePatientSelectionArea()
        {
            // 患者选择标题
            lblPatientTitle = new Label
            {
                Text = "选择患者",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 20),
                Size = new Size(100, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 患者下拉框
            cmbPatients = new ComboBox
            {
                Location = new Point(20, 60),
                Size = new Size(280, 30),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = UIStyleManager.BodyFont
            };

            // 刷新患者按钮
            btnRefreshPatients = new Button
            {
                Text = "刷新",
                Location = new Point(310, 60),
                Size = new Size(60, 30),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = UIStyleManager.BodyFont
            };
            btnRefreshPatients.FlatAppearance.BorderSize = 0;

            // 患者详细信息显示区域
            lblPatientInfo = new Label
            {
                Location = new Point(20, 110),
                Size = new Size(350, 200),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250),
                Font = new Font("微软雅黑", 10),
                Text = "请选择患者查看详细信息",
                Padding = new Padding(10),
                ForeColor = Color.Gray
            };

            // 挂号信息显示
            lblRegistrationInfo = new Label
            {
                Text = "挂号信息",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(20, 330),
                Size = new Size(100, 25),
                ForeColor = UIStyleManager.PrimaryColor
            };

            lblSelectedPatient = CreateInfoLabel("患者：未选择", 20, 365);
            lblSelectedDepartment = CreateInfoLabel("科室：未选择", 20, 395);
            lblSelectedDoctor = CreateInfoLabel("医生：未选择", 20, 425);
            lblRegistrationFee = CreateInfoLabel("挂号费：¥0.00", 20, 455);

            leftPanel.Controls.AddRange(new Control[] {
                lblPatientTitle, cmbPatients, btnRefreshPatients, lblPatientInfo,
                lblRegistrationInfo, lblSelectedPatient, lblSelectedDepartment, 
                lblSelectedDoctor, lblRegistrationFee
            });
        }

        private void CreateDepartmentAndDoctorArea()
        {
            // 科室选择标题
            lblDepartmentTitle = new Label
            {
                Text = "选择科室",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(20, 20),
                Size = new Size(100, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 科室树形控件
            tvDepartments = new TreeView
            {
                Location = new Point(20, 60),
                Size = new Size(350, 280),
                Font = UIStyleManager.BodyFont,
                FullRowSelect = true,
                ShowLines = true,
                ShowPlusMinus = true,
                ShowRootLines = true
            };

            // 医生选择标题
            lblDoctorTitle = new Label
            {
                Text = "选择医生",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                Location = new Point(390, 20),
                Size = new Size(100, 30),
                ForeColor = UIStyleManager.PrimaryColor
            };

            // 医生列表
            dgvDoctors = new DataGridView
            {
                Location = new Point(390, 60),
                Size = new Size(340, 280),
                AutoGenerateColumns = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                Font = UIStyleManager.BodyFont
            };

            // 添加医生列表的列
            dgvDoctors.Columns.Add("doctorName", "医生姓名");
            dgvDoctors.Columns.Add("jobTitleName", "职称");
            dgvDoctors.Columns.Add("mobile", "联系电话");
            dgvDoctors.Columns["doctorName"].Width = 100;
            dgvDoctors.Columns["jobTitleName"].Width = 120;
            dgvDoctors.Columns["mobile"].Width = 120;

            rightPanel.Controls.AddRange(new Control[] {
                lblDepartmentTitle, tvDepartments,
                lblDoctorTitle, dgvDoctors
            });
        }

        private Label CreateInfoLabel(string text, int x, int y)
        {
            return new Label
            {
                Text = text,
                Location = new Point(x, y),
                Size = new Size(350, 25),
                Font = new Font("微软雅黑", 10),
                ForeColor = Color.Black
            };
        }

        private void CreateButtons()
        {
            // 测试连接按钮
            Button btnTestConnection = IconManager.CreateSmallIconButton("测试连接", IconManager.Icons.Search, 100, 45, ButtonStyle.Primary);
            btnTestConnection.Location = new Point(320, 15);
            btnTestConnection.Click += BtnTestConnection_Click;

            // 挂号按钮
            btnRegister = IconManager.CreateSmallIconButton("确认挂号", IconManager.Icons.Save, 120, 45, ButtonStyle.Success);
            btnRegister.Location = new Point(450, 15);
            btnRegister.Enabled = false;

            // 取消按钮
            btnCancel = IconManager.CreateSmallIconButton("取消", IconManager.Icons.Close, 100, 45, ButtonStyle.Danger);
            btnCancel.Location = new Point(590, 15);

            bottomPanel.Controls.Add(btnTestConnection);
            bottomPanel.Controls.Add(btnRegister);
            bottomPanel.Controls.Add(btnCancel);
        }

        private void SetupEventHandlers()
        {
            btnRefreshPatients.Click += BtnRefreshPatients_Click;
            btnRegister.Click += BtnRegister_Click;
            btnCancel.Click += BtnCancel_Click;
            cmbPatients.SelectedIndexChanged += CmbPatients_SelectedIndexChanged;
            tvDepartments.AfterSelect += TvDepartments_AfterSelect;
            dgvDoctors.SelectionChanged += DgvDoctors_SelectionChanged;
        }

        private async void LoadInitialData()
        {
            try
            {
                await LoadPatients();
                await LoadDepartments();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadPatients()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string url = $"http://101.201.170.32:5115/api/Patient/GetPatientsByAccountId?accountId={currentUserId}&includeDeleted=false";
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var result = JsonConvert.DeserializeObject<PatientResponse>(responseContent);
                        if (result.code == 200)
                        {
                            patients = result.data;
                            UpdatePatientComboBox();
                        }
                        else
                        {
                            MessageBox.Show($"获取患者列表失败: {result.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        throw new Exception($"HTTP错误: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载患者列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadDepartments()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string url = "http://101.201.170.32:5115/api/Department/GetDepartmentList";
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var result = JsonConvert.DeserializeObject<DepartmentResponse>(responseContent);
                        if (result.code == 200)
                        {
                            departments = result.data.departments;
                            UpdateDepartmentTree();
                        }
                        else
                        {
                            MessageBox.Show($"获取科室列表失败: {result.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        throw new Exception($"HTTP错误: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载科室列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadDoctors(int deptId)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    string url = $"http://101.201.170.32:5115/api/Doctor/Doctor/GetDoctors?deptId={deptId}&pageIndex=1&pageSize=100";
                    var response = await client.GetAsync(url);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var result = JsonConvert.DeserializeObject<DoctorResponse>(responseContent);
                        if (result.code == 200)
                        {
                            doctors = result.pageData;
                            UpdateDoctorGrid();
                        }
                        else
                        {
                            MessageBox.Show($"获取医生列表失败: {result.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        throw new Exception($"HTTP错误: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载医生列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdatePatientComboBox()
        {
            cmbPatients.Items.Clear();
            foreach (var patient in patients)
            {
                cmbPatients.Items.Add($"{patient.name} - {patient.idCardMasked}");
            }
        }

        private void UpdateDepartmentTree()
        {
            tvDepartments.Nodes.Clear();
            foreach (var dept in departments)
            {
                var parentNode = new TreeNode(dept.departmentName)
                {
                    Tag = dept
                };
                AddChildDepartments(parentNode, dept.children);
                tvDepartments.Nodes.Add(parentNode);
            }
        }

        private void AddChildDepartments(TreeNode parentNode, List<DepartmentInfo> children)
        {
            foreach (var child in children)
            {
                var childNode = new TreeNode(child.departmentName)
                {
                    Tag = child
                };
                AddChildDepartments(childNode, child.children);
                parentNode.Nodes.Add(childNode);
            }
        }

        private void UpdateDoctorGrid()
        {
            dgvDoctors.Rows.Clear();
            foreach (var doctor in doctors)
            {
                dgvDoctors.Rows.Add(doctor.doctorName, doctor.jobTitleName, doctor.mobile);
                dgvDoctors.Rows[dgvDoctors.Rows.Count - 1].Tag = doctor;
            }
        }

        private void UpdateRegistrationInfo()
        {
            // 检查是否所有必要信息都已选择
            bool canRegister = cmbPatients.SelectedIndex >= 0 && selectedDepartment != null && selectedDoctor != null;
            btnRegister.Enabled = canRegister;

            // 更新显示信息
            if (cmbPatients.SelectedIndex >= 0)
            {
                var patient = patients[cmbPatients.SelectedIndex];
                lblSelectedPatient.Text = $"患者：{patient.name}";
            }
            else
            {
                lblSelectedPatient.Text = "患者：未选择";
            }

            if (selectedDepartment != null)
            {
                lblSelectedDepartment.Text = $"科室：{selectedDepartment.departmentName}";
                lblRegistrationFee.Text = $"挂号费：¥{selectedDepartment.registrationFee:F2}";
            }
            else
            {
                lblSelectedDepartment.Text = "科室：未选择";
                lblRegistrationFee.Text = "挂号费：¥0.00";
            }

            if (selectedDoctor != null)
            {
                lblSelectedDoctor.Text = $"医生：{selectedDoctor.doctorName} ({selectedDoctor.jobTitleName})";
            }
            else
            {
                lblSelectedDoctor.Text = "医生：未选择";
            }
        }

        // 事件处理方法
        private async void BtnRefreshPatients_Click(object sender, EventArgs e)
        {
            await LoadPatients();
        }

        private void CmbPatients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPatients.SelectedIndex >= 0)
            {
                var patient = patients[cmbPatients.SelectedIndex];
                lblPatientInfo.Text = $"姓名：{patient.name}\n" +
                                     $"性别：{patient.sexText}\n" +
                                     $"年龄：{patient.age}岁\n" +
                                     $"联系电话：{patient.contactInfo}\n" +
                                     $"身份证号：{patient.idCardMasked}\n" +
                                     $"地址：{patient.currentAddress}";
                lblPatientInfo.ForeColor = Color.Black;
            }
            else
            {
                lblPatientInfo.Text = "请选择患者查看详细信息";
                lblPatientInfo.ForeColor = Color.Gray;
            }
            UpdateRegistrationInfo();
        }

        private async void TvDepartments_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag is DepartmentInfo dept)
            {
                selectedDepartment = dept;
                selectedDoctor = null; // 重置医生选择
                await LoadDoctors(dept.id);
                UpdateRegistrationInfo();
            }
        }

        private void DgvDoctors_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDoctors.SelectedRows.Count > 0)
            {
                selectedDoctor = dgvDoctors.SelectedRows[0].Tag as DoctorInfo;
                UpdateRegistrationInfo();
            }
        }

        private async void BtnRegister_Click(object sender, EventArgs e)
        {
            if (cmbPatients.SelectedIndex < 0 || selectedDepartment == null || selectedDoctor == null)
            {
                MessageBox.Show("请完成患者、科室和医生的选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var patient = patients[cmbPatients.SelectedIndex];
            var confirmMessage = $"确认挂号信息：\n\n" +
                               $"患者：{patient.name}\n" +
                               $"科室：{selectedDepartment.departmentName}\n" +
                               $"医生：{selectedDoctor.doctorName}\n" +
                               $"挂号费：¥{selectedDepartment.registrationFee:F2}\n\n" +
                               $"是否确认挂号？";

            if (MessageBox.Show(confirmMessage, "确认挂号", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                await RegisterPatient(patient);
            }
        }

        private async Task RegisterPatient(PatientInfo patient)
        {
            try
            {
                // 禁用挂号按钮防止重复提交
                btnRegister.Enabled = false;
                btnRegister.Text = "挂号中...";

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    // 构建挂号数据
                    var registrationData = new
                    {
                        card_no = "",
                        patient_id = patient.id,
                        doctor_id = selectedDoctor.id,
                        dept_id = selectedDepartment.id,
                        visit_date = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                        fee = selectedDepartment.registrationFee,
                        createPeople = string.IsNullOrEmpty(currentUserName) ? "系统用户" : currentUserName
                    };

                    var json = JsonConvert.SerializeObject(registrationData, Formatting.Indented);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 调用挂号API
                    string url = "http://101.201.170.32:5166/api/Registration";
                    
                    // 调试信息（仅在开发环境显示）
                    System.Diagnostics.Debug.WriteLine("=== 开始挂号API请求 ===");
                    System.Diagnostics.Debug.WriteLine($"URL: {url}");
                    System.Diagnostics.Debug.WriteLine($"请求数据: {json}");
                    
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    // 调试信息（仅在开发环境显示）
                    System.Diagnostics.Debug.WriteLine("=== 挂号API响应 ===");
                    System.Diagnostics.Debug.WriteLine($"状态码: {response.StatusCode}");
                    System.Diagnostics.Debug.WriteLine($"响应内容: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        // 检查响应体中的code字段
                        try
                        {
                            dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                            if (apiResponse?.code == 200)
                            {
                                string successMessage = "挂号成功！";
                                if (apiResponse?.msg != null)
                                {
                                    successMessage = apiResponse.msg.ToString();
                                }
                                if (apiResponse?.data?.registrationId != null)
                                {
                                    successMessage += $"\n挂号ID: {apiResponse.data.registrationId}";
                                }
                                
                                MessageBox.Show(successMessage, "挂号成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.Close();
                            }
                            else
                            {
                                // API返回失败
                                string errorMessage = "挂号失败";
                                if (apiResponse?.msg != null)
                                {
                                    errorMessage = apiResponse.msg.ToString();
                                }
                                MessageBox.Show($"挂号失败: {errorMessage}", "挂号失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        catch (Exception parseEx)
                        {
                            // JSON解析失败，按成功处理
                            MessageBox.Show("挂号可能成功，但响应格式异常", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Close();
                        }
                    }
                    else
                    {
                        // 构建详细的错误信息
                        string errorMessage = $"挂号失败\n\n";
                        errorMessage += $"状态码: {response.StatusCode}\n";
                        errorMessage += $"状态描述: {response.ReasonPhrase}\n\n";
                        
                        // 尝试解析服务器返回的错误信息
                        if (!string.IsNullOrEmpty(responseContent))
                        {
                            try
                            {
                                dynamic errorResponse = JsonConvert.DeserializeObject(responseContent);
                                if (errorResponse?.message != null)
                                {
                                    errorMessage += $"错误信息: {errorResponse.message}\n";
                                }
                                else if (errorResponse?.msg != null)
                                {
                                    errorMessage += $"错误信息: {errorResponse.msg}\n";
                                }
                                else if (errorResponse?.error != null)
                                {
                                    errorMessage += $"错误信息: {errorResponse.error}\n";
                                }
                                else
                                {
                                    errorMessage += $"服务器响应: {responseContent}\n";
                                }
                            }
                            catch
                            {
                                errorMessage += $"服务器响应: {responseContent}\n";
                            }
                        }
                        
                        errorMessage += $"\n请求URL: {url}\n";
                        errorMessage += $"请求数据: {json}";
                        
                        MessageBox.Show(errorMessage, "挂号失败 - 详细信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string errorDetails = $"网络请求失败\n\n";
                errorDetails += $"错误类型: 网络连接错误\n";
                errorDetails += $"错误信息: {ex.Message}\n\n";
                if (ex.InnerException != null)
                {
                    errorDetails += $"内部错误: {ex.InnerException.Message}\n";
                }
                errorDetails += $"请检查:\n";
                errorDetails += $"1. 网络连接是否正常\n";
                errorDetails += $"2. 服务器是否在运行 (http://101.201.170.32:5166)\n";
                errorDetails += $"3. 防火墙是否阻止连接";
                
                MessageBox.Show(errorDetails, "网络错误 - 详细信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TaskCanceledException ex)
            {
                string errorDetails = $"请求超时\n\n";
                errorDetails += $"错误信息: {ex.Message}\n\n";
                errorDetails += $"可能原因:\n";
                errorDetails += $"1. 服务器响应时间过长\n";
                errorDetails += $"2. 网络连接不稳定\n";
                errorDetails += $"3. 服务器负载过高\n\n";
                errorDetails += $"建议: 请稍后重试";
                
                MessageBox.Show(errorDetails, "超时错误 - 详细信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                string errorDetails = $"系统错误\n\n";
                errorDetails += $"错误类型: {ex.GetType().Name}\n";
                errorDetails += $"错误信息: {ex.Message}\n\n";
                if (ex.InnerException != null)
                {
                    errorDetails += $"内部错误: {ex.InnerException.Message}\n";
                }
                errorDetails += $"堆栈跟踪: {ex.StackTrace}";
                
                MessageBox.Show(errorDetails, "系统错误 - 详细信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复挂号按钮状态
                btnRegister.Enabled = true;
                btnRegister.Text = "确认挂号";
            }
        }

        private async void BtnTestConnection_Click(object sender, EventArgs e)
        {
            try
            {
                var testButton = sender as Button;
                testButton.Enabled = false;
                testButton.Text = "测试中...";

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 测试基本连接
                    string baseUrl = "http://101.201.170.32:5166";
                    string testUrl = $"{baseUrl}/api/Department/GetDepartmentList"; // 使用已知可用的API
                    
                    System.Diagnostics.Debug.WriteLine($"=== 测试API连接 ===");
                    System.Diagnostics.Debug.WriteLine($"测试URL: {testUrl}");
                    
                    var response = await client.GetAsync(testUrl);
                    string responseContent = await response.Content.ReadAsStringAsync();
                    
                    System.Diagnostics.Debug.WriteLine($"测试结果: {response.StatusCode}");
                    System.Diagnostics.Debug.WriteLine($"响应内容: {responseContent}");
                    
                    string testResult = $"API连接测试结果\n\n";
                    testResult += $"服务器地址: {baseUrl}\n";
                    testResult += $"测试接口: /api/Department/GetDepartmentList\n";
                    testResult += $"状态码: {response.StatusCode}\n";
                    testResult += $"状态描述: {response.ReasonPhrase}\n\n";
                    
                    if (response.IsSuccessStatusCode)
                    {
                        testResult += "✅ 连接成功!\n";
                        testResult += "服务器响应正常，可以进行挂号操作。\n\n";
                        
                        // 进一步测试挂号API是否存在
                        try
                        {
                            string registrationTestUrl = $"{baseUrl}/api/Registration";
                            var optionsRequest = new HttpRequestMessage(HttpMethod.Options, registrationTestUrl);
                            var optionsResponse = await client.SendAsync(optionsRequest);
                            
                            testResult += $"挂号API测试:\n";
                            testResult += $"URL: {registrationTestUrl}\n";
                            testResult += $"状态: {optionsResponse.StatusCode}\n";
                            
                            if (optionsResponse.StatusCode == System.Net.HttpStatusCode.MethodNotAllowed ||
                                optionsResponse.StatusCode == System.Net.HttpStatusCode.OK ||
                                optionsResponse.StatusCode == System.Net.HttpStatusCode.NoContent)
                            {
                                testResult += "✅ 挂号API端点存在\n";
                            }
                            else
                            {
                                testResult += "⚠️ 挂号API可能不存在或不支持POST方法\n";
                            }
                        }
                        catch (Exception apiEx)
                        {
                            testResult += $"⚠️ 挂号API测试失败: {apiEx.Message}\n";
                        }
                        
                        MessageBox.Show(testResult, "连接测试成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        testResult += "❌ 连接失败!\n";
                        testResult += $"服务器返回错误状态码。\n\n";
                        testResult += $"响应内容: {responseContent}";
                        
                        MessageBox.Show(testResult, "连接测试失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string errorDetails = $"网络连接测试失败\n\n";
                errorDetails += $"错误类型: 网络连接错误\n";
                errorDetails += $"错误信息: {ex.Message}\n\n";
                errorDetails += $"可能原因:\n";
                errorDetails += $"1. 服务器未启动 (http://101.201.170.32:5166)\n";
                errorDetails += $"2. 端口5166被其他程序占用\n";
                errorDetails += $"3. 防火墙阻止连接\n";
                errorDetails += $"4. 服务器配置错误\n\n";
                errorDetails += $"建议:\n";
                errorDetails += $"1. 检查后端API服务是否正在运行\n";
                errorDetails += $"2. 确认端口号是否正确";
                
                MessageBox.Show(errorDetails, "连接测试 - 网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TaskCanceledException ex)
            {
                MessageBox.Show($"连接测试超时\n\n请检查服务器是否响应缓慢或网络连接是否正常。", "连接测试 - 超时", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                string errorDetails = $"连接测试发生错误\n\n";
                errorDetails += $"错误类型: {ex.GetType().Name}\n";
                errorDetails += $"错误信息: {ex.Message}";
                
                MessageBox.Show(errorDetails, "连接测试 - 系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                var testButton = sender as Button;
                testButton.Enabled = true;
                testButton.Text = "测试连接";
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

    // 数据模型类
    public class PatientInfo
    {
        public int id { get; set; }
        public int accountId { get; set; }
        public string name { get; set; }
        public bool sex { get; set; }
        public string sexText { get; set; }
        public DateTime dateOfBirth { get; set; }
        public int age { get; set; }
        public string contactInfo { get; set; }
        public string idCard { get; set; }
        public string idCardMasked { get; set; }
        public string currentAddress { get; set; }
        public string infectiousDiseaseHistory { get; set; }
        public string geneticDiseaseInfo { get; set; }
        public string createPeople { get; set; }
        public DateTime createTime { get; set; }
    }

    public class DepartmentInfo
    {
        public int id { get; set; }
        public string departmentName { get; set; }
        public string departmentAddr { get; set; }
        public decimal registrationFee { get; set; }
        public string type { get; set; }
        public bool isOnline { get; set; }
        public bool isEmergencyService { get; set; }
        public int parentId { get; set; }
        public string remark { get; set; }
        public DateTime createTime { get; set; }
        public List<DepartmentInfo> children { get; set; } = new List<DepartmentInfo>();
    }

    public class DoctorInfo
    {
        public int id { get; set; }
        public string doctorCode { get; set; }
        public string doctorName { get; set; }
        public int deptId { get; set; }
        public string departmentName { get; set; }
        public int jobTitleId { get; set; }
        public string jobTitleName { get; set; }
        public string mobile { get; set; }
        public string status { get; set; }
        public string photo { get; set; }
        public string occupationCertificate { get; set; }
        public string rankCertificate { get; set; }
        public int hospitalId { get; set; }
        public string hospitalName { get; set; }
    }

    public class PatientResponse
    {
        public string msg { get; set; }
        public int code { get; set; }
        public List<PatientInfo> data { get; set; }
    }

    public class DepartmentResponse
    {
        public string msg { get; set; }
        public int code { get; set; }
        public DepartmentData data { get; set; }
    }

    public class DepartmentData
    {
        public List<DepartmentInfo> departments { get; set; }
    }

    public class DoctorResponse
    {
        public int totaCount { get; set; }
        public int totaPage { get; set; }
        public List<DoctorInfo> pageData { get; set; }
        public string msg { get; set; }
        public int code { get; set; }
        public object data { get; set; }
    }
} 